package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.dao.TaskDao;
import com.lkd.entity.AbstractEntity;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.utils.DateUtil;
import com.lkd.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {

        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }

        //判断售货机状态和工单类型是否相符合   vm0:未投放;1-运营;3-撤机
        //1	投放工单
        //2	补货工单
        //3	维修工单
        //4	撤机工单
        if (taskViewModel.getProductType()==1 && vm.getVmStatus()==1){
            throw new LogicException("该设备已在运营");
        }

        if (taskViewModel.getProductType()==2&&vm.getVmStatus()!=1){
            throw new LogicException("该设备不在运营状态");
        }

        if (taskViewModel.getProductType()==4&&vm.getVmStatus()!=1){
            throw new LogicException("该设备不在运营状态");
        }



        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }

        //同一台设备下是否存在未完成的工单
        LambdaQueryWrapper<TaskEntity> w = new LambdaQueryWrapper<>();
        w.eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode())
                .eq(TaskEntity::getProductTypeId, taskViewModel.getProductType())
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        List<TaskEntity> list = this.list(w);
        System.out.println("------------------------");
        System.out.println(list.size());
        System.out.println("------------------------");

        if (list.size()>0){
            throw new LogicException("有同类型工单未完成");
        }


        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(  vm.getRegionId() );//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录

        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        return true;
    }


    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }

    /**
     * accept接单
     * @param id
     * @param userId
     * @return
     */
    @Override
    public boolean accept(Long id,Integer userId) {
        TaskEntity task = this.getById(id);  //查询工单
        if(task.getUserId()!=userId){
            throw new LogicException("您无权限操作此订单！");

        }
        if (task.getTaskStatus()!=1){
            throw new LogicException("此订单非待办订单无法接受！");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    /**
     * 取消订单
     * @param id
     * @param cancelVM
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM,Integer userId) {
        TaskEntity task = this.getById(id);  //查询工单
        if(task.getUserId()!=userId){
            throw new LogicException("您无权限操作此订单！");

        }
        if (task.getTaskStatus()>2){
            throw new LogicException("订单已完成或取消，无法取消！");

        }
        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        return this.updateById(task);
    }

    /**
     * 完成工单
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(long id,Integer userId) {
        TaskEntity taskEntity = this.getById(id);
        if(taskEntity.getUserId()!=userId){
            throw new LogicException("您无权限操作此订单！");

        }
        if (taskEntity.getTaskStatus()>2){
            throw new LogicException("订单已完成或取消，无法取消！");

        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);
        return true;
    }

    @Override
    public List<TaskReportInfoVO> taskReportInfo(LocalDateTime startTime, LocalDateTime endTime) {
        //# 运营总单
        Integer allP = mySelect(startTime, endTime, 2, null);
        //# 运营完成订单
        Integer finishP = mySelect(startTime, endTime, 2, 4);
        //# 运营拒绝订单
        //select count(task_id) from tb_task where
        //    update_time between "2022-07-11 00:47:19" and "2022-07-11 23:47:19"
        //    and task_status=3
        //    and product_type_id=2;
        Integer refuseP = mySelect(startTime, endTime, 2, 3);

        //# 维护总单
        //select count(task_id) from tb_task
        //where update_time between "2022-07-11 00:47:19" and "2022-07-11 16:47:19"
        //  and product_type_id!=2;
        Integer wAllP = mySelect(startTime, endTime, 0, null);
        //# 维护完成订单
        //select count(task_id) from tb_task where
        //    update_time between "2022-07-11 00:47:19" and "2022-07-11 23:47:19"
        //    and product_type_id!=2
        //    and task_status=4;
        Integer wfinishP = mySelect(startTime, endTime, 0, 4);

        //# 维护拒绝订单
        //select count(task_id) from tb_task where
        //    update_time between "2022-07-11 00:47:19" and "2022-07-11 23:47:19"
        //    and task_status=3
        //    and product_type_id!=2;
        Integer wrefuseP = mySelect(startTime, endTime, 0, 3);

        Integer operatorCount = userService.getOperatorCount();
        Integer repairerCount = userService.getRepairerCount();

        //返回结果构建
        List<TaskReportInfoVO> result = new ArrayList<>();
        //运营
        TaskReportInfoVO r1 = new TaskReportInfoVO();
        //维护
        TaskReportInfoVO r2 = new TaskReportInfoVO();

        r1.setTotal(allP);
        r1.setCompletedTotal(finishP);
        r1.setCancelTotal(refuseP);
        r1.setWorkerCount(operatorCount);
        r1.setRepair(false);
        result.add(r1);
        r2.setTotal(wAllP);
        r2.setCompletedTotal(wfinishP);
        r2.setCancelTotal(wrefuseP);
        r2.setWorkerCount(repairerCount);
        r2.setRepair(true);
        result.add(r2);

        return result;
    }

    /**
     * top10
     * @param startTime
     * @param endTime
     * @param isRepair
     * @param regionId
     * @return
     */
    @Override
    public List<UserWorkVO> getUserWorkTop10(LocalDate startTime, LocalDate endTime, boolean isRepair, String regionId) {
        QueryWrapper<TaskEntity> w = new QueryWrapper<>();
        w.select("count(user_id) as user_id,user_name")
                .lambda()
                .ge(AbstractEntity::getUpdateTime,startTime)
                .le(AbstractEntity::getUpdateTime,endTime)
                .eq(TaskEntity::getTaskStatus,4)
                .groupBy(TaskEntity::getUserName)
                .orderByDesc(TaskEntity::getUserId)
                .last("limit 10");

        long parseLong = Long.parseLong(regionId);
        if(parseLong >0){
            w.lambda().eq(TaskEntity::getRegionId,parseLong);
        }
        if(isRepair){
            w.lambda().ne(TaskEntity::getProductTypeId,2);
        }else {
            w.lambda().eq(TaskEntity::getProductTypeId,2);
        }
        List<TaskEntity> list = this.list(w);
        //构建返回对象
        List<UserWorkVO> users = new ArrayList<>();
        for (TaskEntity entity : list) {
            UserWorkVO userVO = new UserWorkVO();
            userVO.setUserName(entity.getUserName());
            userVO.setWorkCount(entity.getUserId());
            users.add(userVO);
        }

        return users;
    }

    @Override
    public List<TaskCollectVO> collectVOList(LocalDate parse, LocalDate parse1) {
        ArrayList<TaskCollectVO> vos = new ArrayList<>();

        try {
            List<String> dates = DateUtil.findDates(parse.toString(), parse1.toString());
            for (String date : dates) {
                LocalDate date1 = LocalDate.parse(date, DateTimeFormatter.ISO_DATE);
                TaskCollectVO vo = new TaskCollectVO();
                vo.setProgressCount(myCount(date1,2));//ing
                vo.setFinishCount(myCount(date1,4));//finish
                vo.setCancelCount(myCount(date1,3));//refuse
                vos.add(vo);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return vos;
    }

    @Override
    public UserWorkVO getUserWork(Integer userId, LocalDateTime start, LocalDateTime end) {
        var userWork = new UserWorkVO();
        userWork.setUserId(userId);
        //获取工单总数
        var total = this.getCountByUserId(userId,null,start.toLocalDate(),end);
        userWork.setTotal(total);
        //获取进行中得工单数
        var progressTotal = this.getCountByUserId(userId,2,start.toLocalDate(),end);
        userWork.setProgressTotal(progressTotal);
        //获取用户完成工单数
        var workCount = this.getCountByUserId(userId,4,start.toLocalDate(),end);
        userWork.setWorkCount(workCount);
        //获取用户拒绝工单数
        var cancelCount = this.getCountByUserId(userId,3,start.toLocalDate(),end);
        userWork.setCancelCount(cancelCount);
        return userWork;
    }


    //根据工单状态，获取工单数
    private Integer getCountByUserId(Integer userId,Integer taskStatus,LocalDate start,LocalDateTime end){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        if(taskStatus != null ){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        if(userId != null) {
            qw.eq(TaskEntity::getUserId,userId);
        }
        return this.count(qw);
    }

    private Integer myCount(LocalDate date, int i) {
        LambdaQueryWrapper<TaskEntity> w = new LambdaQueryWrapper<>();
        w.ge(TaskEntity::getUpdateTime,date).le(TaskEntity::getUpdateTime,date.plusDays(1)).eq(TaskEntity::getTaskStatus,i);

        return  this.count(w);
    }


    private Integer mySelect(LocalDateTime startTime, LocalDateTime endTime, Integer productTypeId, Integer taskStatus) {

        LambdaQueryWrapper<TaskEntity> w = new LambdaQueryWrapper<>();
        w.gt(AbstractEntity::getUpdateTime,startTime).le(AbstractEntity::getUpdateTime,endTime);
        if (productTypeId==2){
            w.eq(TaskEntity::getProductTypeId,2);
            if (taskStatus!=null){
                w.eq(TaskEntity::getTaskStatus,taskStatus);
            }
        }else {
            w.ne(TaskEntity::getProductTypeId,2);
            if (taskStatus!=null){
                w.eq(TaskEntity::getTaskStatus,taskStatus);
            }
        }
        return this.count(w);

    }


}
